package com.ruoyi.canteen.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.canteen.constant.OrderType;
import com.ruoyi.canteen.controller.v1.OrderReturnApiController;
import com.ruoyi.canteen.domain.CanteenCpOrder;
import com.ruoyi.canteen.mapper.CanteenCpOrderMapper;
import com.ruoyi.canteen.vo.OrderShowVo;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.AESUtil;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.weika.domain.CanteenJijuConfig;
import com.ruoyi.weika.service.ICanteenJijuConfigService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.canteen.mapper.CanteenCpOrderReturnMapper;
import com.ruoyi.canteen.domain.CanteenCpOrderReturn;
import com.ruoyi.canteen.service.ICanteenCpOrderReturnService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestParam;

import static com.ruoyi.common.utils.AESUtil.Encrypt;

/**
 * 订单退货Service业务层处理
 * 
 * @author ruoyi
 * @date 2022-04-06
 */
@Service
public class CanteenCpOrderReturnServiceImpl implements ICanteenCpOrderReturnService 
{
    private static final Logger log = LoggerFactory.getLogger(CanteenCpOrderReturnServiceImpl.class);

    @Autowired
    private CanteenCpOrderReturnMapper canteenCpOrderReturnMapper;

    @Autowired
    private CanteenCpOrderMapper canteenCpOrderMapper;

    @Autowired
    private ICanteenJijuConfigService canteenJijuConfigService;

    /**
     * 查询订单退货
     * 
     * @param id 订单退货主键
     * @return 订单退货
     */
    @Override
    public CanteenCpOrderReturn selectCanteenCpOrderReturnById(Long id)
    {
        return canteenCpOrderReturnMapper.selectCanteenCpOrderReturnById(id);
    }

    /**
     * 查询订单退货列表
     * 
     * @param canteenCpOrderReturn 订单退货
     * @return 订单退货
     */
    @Override
    public List<CanteenCpOrderReturn> selectCanteenCpOrderReturnList(CanteenCpOrderReturn canteenCpOrderReturn)
    {
        return canteenCpOrderReturnMapper.selectCanteenCpOrderReturnList(canteenCpOrderReturn);
    }

    /**
     * 新增订单退货
     * 
     * @param canteenCpOrderReturn 订单退货
     * @return 结果
     */
    @Override
    public int insertCanteenCpOrderReturn(CanteenCpOrderReturn canteenCpOrderReturn)
    {
        return canteenCpOrderReturnMapper.insertCanteenCpOrderReturn(canteenCpOrderReturn);
    }

    /**
     * 修改订单退货
     * 
     * @param canteenCpOrderReturn 订单退货
     * @return 结果
     */
    @Override
    public int updateCanteenCpOrderReturn(CanteenCpOrderReturn canteenCpOrderReturn)
    {
        canteenCpOrderReturn.setUpdateTime(DateUtils.getNowDate());
        return canteenCpOrderReturnMapper.updateCanteenCpOrderReturn(canteenCpOrderReturn);
    }

    /**
     * 批量删除订单退货
     * 
     * @param ids 需要删除的订单退货主键
     * @return 结果
     */
    @Override
    public int deleteCanteenCpOrderReturnByIds(Long[] ids)
    {
        return canteenCpOrderReturnMapper.deleteCanteenCpOrderReturnByIds(ids);
    }

    /**
     * 删除订单退货信息
     * 
     * @param id 订单退货主键
     * @return 结果
     */
    @Override
    public int deleteCanteenCpOrderReturnById(Long id)
    {
        return canteenCpOrderReturnMapper.deleteCanteenCpOrderReturnById(id);
    }

    /**
     * 查询当前用户关联门店的退单列表(当日订单)
     * @param mdIds 门店ids
     * @return
     */
    @Override
    public List<OrderShowVo> selectDefaultOrderShowVoList(String mdIds){
        return canteenCpOrderReturnMapper.selectDefaultOrderShowVoList(mdIds);
    }

    /**
     * 驳回退款
     * @param orderId 订单id
     * @param uid 登录用户id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult backReturn(String orderId, String uid){
        CanteenCpOrderReturn canteenCpOrderReturn = new CanteenCpOrderReturn();
        canteenCpOrderReturn.setOrderId(Long.valueOf(orderId));
        List<CanteenCpOrderReturn> list =
                canteenCpOrderReturnMapper.selectCanteenCpOrderReturnList(canteenCpOrderReturn);
        if(list.size() == 1){
            // 1. 更新订单售后（退货）表
            CanteenCpOrderReturn reOrder = list.get(0);
            if(!reOrder.getReturnApplyStatus().equals(1)){
                return new AjaxResult(500,"无法再次审核");
            }
            reOrder.setReturnApplyStatus(OrderType.ORDER_RETURN_SHBTG);
            reOrder.setReturnCheckerId(Long.valueOf(uid));
            reOrder.setCheckTime(new Date());
            reOrder.setUpdateBy(uid);
            reOrder.setUpdateTime(new Date());
            canteenCpOrderReturnMapper.updateCanteenCpOrderReturn(reOrder);
            // 2. 同步更新订单状态表
            canteenCpOrderMapper.updateOrderStatusById(OrderType.ORDER_STATUS_THBTG, Long.valueOf(orderId));
            return new AjaxResult(200,"驳回成功");
        }else{
            //
            return new AjaxResult(500,"无对应退款申请");
        }
    }

    /**
     * 微卡同意退款
     * @param orderId 订单id
     * @param uid 登录用户id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult agreeReturn(String orderId, String uid){
        CanteenCpOrderReturn canteenCpOrderReturn = new CanteenCpOrderReturn();
        canteenCpOrderReturn.setOrderId(Long.valueOf(orderId));
        List<CanteenCpOrderReturn> list =
                canteenCpOrderReturnMapper.selectCanteenCpOrderReturnList(canteenCpOrderReturn);
        if(list.size() == 1){

            CanteenCpOrderReturn reOrder = list.get(0);
            if(!reOrder.getReturnApplyStatus().equals(1)){
                return new AjaxResult(500,"无法再次审核");
            }
            CanteenCpOrder order = canteenCpOrderMapper.selectCanteenCpOrderById(Long.valueOf(orderId));
            // 职工退款
            if(StringUtils.isNotEmpty(order.getUserCode()) && order.getPayFlag().equals("1")
                    && order.getOrderStatus().toString().equals(OrderType.ORDER_STATUS_THDSH.toString())){
                AjaxResult result = this.refundByWk(order.getOrderNo(), order.getMdId().toString());
                log.info("调用退款接口返回", result);
                if(result.get("code").equals(200)){
                    JSONObject jsonObject = JSONObject.parseObject(result.get("msg").toString());
                    if(jsonObject.get("code").equals(0)){
                        // 1. 更新订单售后（退货）表
                        // TODO 获取调用退款接口返回值
                        reOrder.setReturnResult(jsonObject.toString());
                        reOrder.setReturnApplyStatus(OrderType.ORDER_RETURN_SHTG);
                        reOrder.setReturnCheckerId(Long.valueOf(uid));
                        reOrder.setCheckTime(new Date());
                        reOrder.setUpdateBy(uid);
                        reOrder.setUpdateTime(new Date());
                        canteenCpOrderReturnMapper.updateCanteenCpOrderReturn(reOrder);
                        // 2. 同步更新订单状态表
                        canteenCpOrderMapper.updateOrderStatusById(OrderType.ORDER_STATUS_THWC, Long.valueOf(orderId));
                        log.info("订单退款成功：",reOrder);
                        return new AjaxResult(200,"退款成功");
                    }else{
                        return AjaxResult.error(jsonObject.get("message").toString());
                    }
                }else{
                    JSONObject jsonObject = JSONObject.parseObject(result.get("msg").toString());
                    return AjaxResult.error(jsonObject.get("message").toString());
                }
            }else {
                return new AjaxResult(500,"暂不支持退款");
            }
        }else{
            //
            return new AjaxResult(500,"无对应退款申请");
        }
    }

    // 职工微卡退款
    public AjaxResult refundByWk(String order_id, String mdId)
    {
        log.info("退款入参:"+order_id+"门店id:+"+mdId);

        CanteenJijuConfig config = canteenJijuConfigService.selectCanteenJijuConfigByMdId(Long.parseLong(mdId) );
        if(config !=null)
        {
            log.info("获取配置信息成功");
            long timestamp = System.currentTimeMillis()/1000;
            String cSrc = AESUtil.getStringRandom(10)+":"+timestamp+":1";
            try {

                String enString =  Encrypt(cSrc, config.getKey(), config.getKey().substring(0,16));
                Map<String,Object> map = new HashMap<>();
                map.put("refund_id",order_id+"_refund");
                map.put("order_id",order_id);

                Map<String,String> headerMap = new HashMap<>();
                headerMap.put("Content-type", "application/json;charset=UTF-8");
                headerMap.put("authorization","WxToken "+config.getJijuNo()+":"+enString);
                //log.info("authorization:"+"WxToken "+config.getJijuNo()+":"+enString);
                String rs = HttpUtils.https("https://payapi.weixiao.qq.com/refund",map,headerMap,enString);
                if(rs != null){
                    return AjaxResult.success(rs);
                }
                else
                    return AjaxResult.error("调用退款接口失败！");

            } catch (Exception e) {
                e.printStackTrace();
                return AjaxResult.error("error",e.getMessage());
            }
        }else
        {
            log.info("获取配置信息失败");
            return AjaxResult.error("error","获取配置信息失败!");
        }
    }

    /**
     * 微信退款系统表中数据变更
     * 1 订单表状态
     * 2 退单申请表状态
     * @param orderNo 订单编号
     * @param userId 操作人微信id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult refundBySys(String orderNo, Long userId, JSONObject jsonObject){
        CanteenCpOrder queryOrder = new CanteenCpOrder();
        queryOrder.setOrderNo(orderNo);
        List<CanteenCpOrder> orderList = canteenCpOrderMapper.selectCanteenCpOrderList(queryOrder);
        CanteenCpOrder curOrder = orderList.get(0);
        if(curOrder.getPayFlag().equals("1")
                && curOrder.getOrderStatus().toString().equals(OrderType.ORDER_STATUS_THDSH.toString())){
            Long orderId = curOrder.getId();
            CanteenCpOrderReturn queryReturnOrder = new CanteenCpOrderReturn();
            queryReturnOrder.setOrderId(orderId);
            List<CanteenCpOrderReturn> returnOrderList =
                    canteenCpOrderReturnMapper.selectCanteenCpOrderReturnList(queryReturnOrder);
            if(returnOrderList.size() == 1) {
                CanteenCpOrderReturn reOrder = returnOrderList.get(0);
                reOrder.setReturnResult(jsonObject.toString());
                reOrder.setReturnApplyStatus(OrderType.ORDER_RETURN_SHTG);
                reOrder.setReturnCheckerId(Long.valueOf(userId));
                reOrder.setCheckTime(new Date());
                reOrder.setUpdateBy(userId.toString());
                reOrder.setUpdateTime(new Date());
                canteenCpOrderReturnMapper.updateCanteenCpOrderReturn(reOrder);
                // 2. 同步更新订单状态表
                canteenCpOrderMapper.updateOrderStatusById(OrderType.ORDER_STATUS_THWC, orderId);
                log.info("订单退款成功：", reOrder);
                return new AjaxResult(200, "退款成功");
            }else{
                canteenCpOrderMapper.updateOrderStatusById(OrderType.ORDER_STATUS_THWC, orderId);
                log.error("无对应退款申请：", curOrder.toString());
                return new AjaxResult(500,"无对应退款申请");
            }
        }else {
            canteenCpOrderMapper.updateOrderStatusById(OrderType.ORDER_STATUS_THWC, curOrder.getId());
            log.error("订单信息有误：", curOrder.toString());
            return new AjaxResult(500,"订单信息有误");
        }
    }

}
